# 访问openapi
# -*- coding: utf-8 -*-
"""
    third_weather.py
    ~~~~~~~~~

    使用心知天气数据查询天气

    :date: 2020-02-10 15:56:00
    :author: by jiangdg
"""

import requests
import json

KEY = 'b3d0f53b57a94aeca711ea11698315f6'

LOCATION_API = 'https://geoapi.qweather.com/v2/city/lookup'
WEATER_API = 'https://devapi.qweather.com/v7/weather/now'


def get_weather(location):
    location_data = requests.get(LOCATION_API, params={
        'key': KEY,
        'location': location
    }, timeout=2)
    locations = location_data.json()['location']
    if not location:
        return '查询不到当前城市的天气'
    location_id = locations[0]['id']
    weather_data = requests.get(WEATER_API, params={
        'key': KEY,
        'location': location_id
    }, timeout=2)
    weather_data = weather_data.json()
    if not weather_data or not weather_data['now'] or not weather_data['now']['text']:
        return '查询不到当前城市的天气'
    weather_data = weather_data['now']
    temperature = weather_data['temp']
    desc = weather_data['text']
    return '%s\t%s\t当前温度%s℃' % (location,desc, temperature)

